//
//  TongJiBaoBiaoViewController.m
//  YaoHeAPP
//
//  Created by 杨亚森 on 16/6/23.
//  Copyright © 2016年 mac. All rights reserved.
//

#import "TongJiBaoBiaoViewController.h"
#import "Masonry.h"
#import "TongJiBaoBiaoListViewController.h"
#import "PCCircle.h"
#import "MJExtension.h"
#import "Controller.h"
#import "TongJiResultModel.h"
#import "StatisticsCountModel.h"
#import "TongJiBaoBiaoItemTableViewCell.h"
#import "StatisticsModel.h"
#import "CustomDatePickerView.h"
#import "SVPullToRefresh.h"
#import "NSDate+DateFormatter.h"
#import "CustomPaiXuPickerView.h"
#import "UILabel+StringFrame.h"
#import "labelview.h"

#define kOneThirdWidth self.view.width/3
#define kFiveLabelWidth 50
#define kMarginLeft (self.view.width-20-kFiveLabelWidth*5)/4
#define kTongJiBaoBiaoItemTableViewCell @"TongJiBaoBiaoItemTableViewCell"

typedef enum : NSUInteger {
    day = 1,
    weak = 7,
    month = 30,
} KeyType;

typedef enum : NSUInteger {
    timeTop2Bottom = 0,                         // 按时间从高到低
    timeBottom2Top = 1,                         // 按时间从低到高
    orderNumberBottom2Top = 2,                  // 按成单数从低到高
    orderNumberTop2Bottom = 3,                  // 按成单数从高到低
} PaiXuMethod;                                  // 根据返回的row参数 对应排序方法

@interface TongJiBaoBiaoViewController () <UITableViewDataSource, UITableViewDelegate, UIGestureRecognizerDelegate> {
    KeyType _keyType;
    NSString *_keyDate;
    NSString *_nowDateString;                                       // 当前日子字符串
    PaiXuMethod _paiXuMethod;                                        // 排序算法
    labelview *la;//无数据显示的页面
}

@property (nonatomic, strong) UIView *navcBar;                       // 导航栏
@property (nonatomic, strong) PCCircle *pcCircle;                    // 圆环
@property (nonatomic, strong) UILabel *yearLabel;                    // 年Label
@property (nonatomic, strong) UILabel *monthLabel;                   // 月Label
@property (nonatomic, strong) UILabel *numberOfOrderLabel;           // 成单数Label
@property (nonatomic, strong) UILabel *compareOrderLabel;            // 同比单数Label
@property (nonatomic, strong) UIImageView *jiantouImage;             //箭头图片
@property (nonatomic, strong) UITableView *baobiaoTableView;         // 报表TableView
@property (nonatomic, strong) TongJiResultModel *tongJiResultModel;  // 数据模型model
@property (nonatomic, strong) NSMutableArray *dataSourceArray;       // tableView数据源
@property (nonatomic, strong) UIView *mengbanView;                   // 蒙版View
@property (nonatomic, strong) UIWindow *window;                      // 获取窗口对象
@property (nonatomic, strong) UITapGestureRecognizer *tapGestureRecognizer;         // 点击手势
@property (nonatomic, strong) CustomDatePickerView *customDatePickerView;           // 弹出时间选择框View
@property (nonatomic, strong) CustomPaiXuPickerView *customPaiXuPickerView;         // 弹出排揎选择
@property (nonatomic, strong) UILabel *paimingLabel;                                //日排名
@property (nonatomic, strong) UIButton *paixuButton;                                //排序按钮
@property (nonatomic, strong) NSMutableArray *customDatePickerViewDataSourceArray;  // 日期数据源
@property (nonatomic, strong) NSMutableDictionary *customDatePickerViewDataSourceDictionary; // 日期数据源

@end

@implementation TongJiBaoBiaoViewController

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    [[self rdv_tabBarController] setTabBarHidden:YES animated:YES];
}

- (void)viewWillDisappear:(BOOL)animated {
    [super viewWillDisappear:animated];
    [[self rdv_tabBarController] setTabBarHidden:NO animated:YES];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    
    //加一个导航条
    UIView *navcBar = [[UIView alloc] init];
    //声明一个背景图片
    UIImage *backgroundImage = [UIImage imageNamed:@"jianbianimg"];
    //将刚刚生成的图片转换为UIColor对象。这样便可以实现平铺了。
    [navcBar setBackgroundColor:[UIColor colorWithPatternImage:backgroundImage]];
    navcBar.clipsToBounds = YES;
    [self.view addSubview:navcBar];
    [navcBar mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.offset(0);   make.left.offset(0);
        make.height.offset(280);  make.right.offset(0);
    }];
    self.navcBar = navcBar;
    
    //导航条标题
    UILabel *titleLabel = [[UILabel alloc] init];
    titleLabel.text = @"统计报表";
    titleLabel.textAlignment = NSTextAlignmentCenter;
    titleLabel.textColor = [UIColor whiteColor];
    [navcBar addSubview:titleLabel];
    [titleLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.offset(25);
        make.left.offset(self.view.frame.size.width/2-70);
        make.width.offset(140);
        make.height.offset(30);
    }];
    
    //返回按钮
    UIButton *leftButton = [UIButton buttonWithType:UIButtonTypeCustom];
    [leftButton setBackgroundImage:[UIImage imageNamed:@"return"] forState:UIControlStateNormal];
    [leftButton addTarget:self action:@selector(backLogin) forControlEvents:UIControlEventTouchUpInside];
    [navcBar addSubview:leftButton];
    [leftButton mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.offset(6);
        make.width.offset(30);
        make.height.offset(28);
        make.top.offset(25);
    }];
    
    NSArray *segmentItemsArray = [NSArray arrayWithObjects:@"日分析", @"周分析", @"月分析", nil];
    UISegmentedControl *segmentControl = [[UISegmentedControl alloc] initWithItems:segmentItemsArray];
    segmentControl.frame = CGRectMake(10, 60, self.view.width-20, 24);
    segmentControl.tintColor = RGBCOLOR(109, 205, 226);
    segmentControl.selectedSegmentIndex = 0;
    [segmentControl addTarget:self action:@selector(segmentAction:)forControlEvents:UIControlEventValueChanged];
    [navcBar addSubview:segmentControl];
    
    //修改字体的默认颜色与选中颜色
    NSDictionary *dic = @{NSFontAttributeName:[UIFont fontWithName:@"Helvetica" size:16.f],
                          NSForegroundColorAttributeName: [UIColor whiteColor]};
    [segmentControl setTitleTextAttributes:dic forState:UIControlStateSelected];
    
    NSDictionary* unselectedTextAttributes = @{NSFontAttributeName:[UIFont fontWithName:@"Helvetica" size:16.f],
                                               NSForegroundColorAttributeName: [UIColor lightTextColor]};
    [segmentControl setTitleTextAttributes:unselectedTextAttributes forState:UIControlStateNormal];
    segmentControl.layer.masksToBounds = YES;
    segmentControl.layer.cornerRadius = 10;
    segmentControl.layer.borderWidth = 2;
    segmentControl.layer.borderColor = RGBCOLOR(120, 205, 226).CGColor;
    
    NSDate *nowDate = [NSDate date];
    _nowDateString = [NSDate formatDate:nowDate];
    NSArray *tempArray = [NSArray array];
    if (_nowDateString) {
        tempArray = [_nowDateString componentsSeparatedByString:@"-"];
    }
    // 修改参数值 把当前日期定为 yyyy-MM-01
    _nowDateString = [NSString stringWithFormat:@"%@-%@-01", tempArray[0], tempArray[1]];
    
    // 年Label
    UILabel *yearLabel = [[UILabel alloc] initWithFrame:CGRectMake(30, segmentControl.bottom+10, 40, 15)];
    yearLabel.font = Font(11);
    if (tempArray[0] != nil) {
        yearLabel.text = [NSString stringWithFormat:@"%@年", tempArray[0]];
    }
    yearLabel.textColor = [UIColor whiteColor];
    [navcBar addSubview:yearLabel];
    self.yearLabel = yearLabel;
    
    // 小三角图标
    UIImageView *sanjiaoImageView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"whitearrow_down"]];
    sanjiaoImageView.frame = CGRectMake(yearLabel.right+2, segmentControl.bottom+15, 7, 5);
    [navcBar addSubview:sanjiaoImageView];
    
    // 月Label
    UILabel *monthLabel = [[UILabel alloc] initWithFrame:CGRectMake(40, yearLabel.bottom+5, 30, 15)];
    monthLabel.font = Font(12);
    if (tempArray[1] != nil) {
        monthLabel.text = [NSString stringWithFormat:@"%@月", tempArray[1]];
    }
    monthLabel.textColor = [UIColor whiteColor];
    [navcBar addSubview:monthLabel];
    self.monthLabel = monthLabel;
    
    // 透明的button
    UIButton *clearColorButton = [UIButton buttonWithType:UIButtonTypeCustom];
    clearColorButton.backgroundColor = [UIColor clearColor];
    clearColorButton.frame = CGRectMake(30, segmentControl.bottom+10, 45, 35);
    [clearColorButton addTarget:self action:@selector(selectTime) forControlEvents:UIControlEventTouchUpInside];
    [navcBar addSubview:clearColorButton];
    
    // 第一个分割线
    UIView *oneFengexianView = [[UIView alloc] initWithFrame:CGRectMake(kOneThirdWidth, segmentControl.bottom+18, 1, 25)];
    oneFengexianView.backgroundColor = RGBCOLOR(109, 205, 226);
    [navcBar addSubview:oneFengexianView];
    
    // 成单数
    UILabel *chengdanshuLabel = [[UILabel alloc] initWithFrame:CGRectMake(kOneThirdWidth+30, segmentControl.bottom+10, 50, 15)];
    chengdanshuLabel.font = Font(11);
    chengdanshuLabel.text = @"成单数";
    chengdanshuLabel.textAlignment = NSTextAlignmentCenter;
    chengdanshuLabel.textColor = [UIColor whiteColor];
    [navcBar addSubview:chengdanshuLabel];
    
    // 单数
    UILabel *numberOfOrderLabel = [[UILabel alloc] initWithFrame:CGRectMake(kOneThirdWidth+30, chengdanshuLabel.bottom+5, 50, 15)];
    numberOfOrderLabel.font = Font(12);
    numberOfOrderLabel.textAlignment = NSTextAlignmentCenter;
    numberOfOrderLabel.textColor = [UIColor whiteColor];
    [navcBar addSubview:numberOfOrderLabel];
    self.numberOfOrderLabel = numberOfOrderLabel;
    
    // 第二个分割线
    UIView *twoFengexianView = [[UIView alloc] initWithFrame:CGRectMake(kOneThirdWidth*2, segmentControl.bottom+18, 1, 25)];
    twoFengexianView.backgroundColor = RGBCOLOR(109, 205, 226);
    [navcBar addSubview:twoFengexianView];
    
    // 同比
    UILabel *tongbiLabel = [[UILabel alloc] initWithFrame:CGRectMake(kOneThirdWidth*2+30, segmentControl.bottom+10, 50, 15)];
    tongbiLabel.font = Font(11);
    tongbiLabel.text = @"环比";
    tongbiLabel.textAlignment = NSTextAlignmentCenter;
    tongbiLabel.textColor = [UIColor whiteColor];
    [navcBar addSubview:tongbiLabel];
    
    // 增加或减少的单数
    UILabel *compareOrderLabel = [[UILabel alloc] initWithFrame:CGRectMake(kOneThirdWidth*2+30, chengdanshuLabel.bottom+5, 50, 15)];
    compareOrderLabel.font = Font(12);
    compareOrderLabel.textAlignment = NSTextAlignmentCenter;
    compareOrderLabel.textColor = [UIColor whiteColor];
    [navcBar addSubview:compareOrderLabel];
    self.compareOrderLabel = compareOrderLabel;
    
    //右边的图片
    UIImageView *jiantouImage = [[UIImageView alloc] initWithFrame:CGRectMake(compareOrderLabel.right, chengdanshuLabel.bottom+5, 10, 20)];
    jiantouImage.image = [UIImage imageNamed:@"bottomimage"];
    [navcBar addSubview:jiantouImage];
    self.jiantouImage = jiantouImage;
    
    UILabel *paimingLabel = [[UILabel alloc] initWithFrame:CGRectMake(10, 285, 80, 20)];
    paimingLabel.font = Font(13);
    paimingLabel.textColor = [UIColor blackColor];
    paimingLabel.text = @"日成单排名";
    [self.view addSubview:paimingLabel];
    self.paimingLabel=paimingLabel;
    
    UIButton *paixuButton = [UIButton buttonWithType:UIButtonTypeCustom];
    paixuButton.frame = CGRectMake(self.view.width-160, 285, 140, 20);
    [paixuButton setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
    paixuButton.titleLabel.font = Font(13);
    [paixuButton setTitleEdgeInsets:UIEdgeInsetsMake(0,0, 0, 10)];
    [paixuButton setImageEdgeInsets:UIEdgeInsetsMake(2.5, 130, 2.5, 0)];
    [paixuButton setTitle:@"按时间从高到低" forState:UIControlStateNormal];
    [paixuButton setImage:[UIImage imageNamed:@"fromtobottomtotop"] forState:UIControlStateNormal];
    [paixuButton addTarget:self action:@selector(selectPaiXuMethod) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:paixuButton];
    self.paixuButton=paixuButton;
    
    UIView *firstLineView = [[UIView alloc] initWithFrame:CGRectMake(0, paimingLabel.bottom+3, self.view.width, 0.5)];
    firstLineView.backgroundColor = RGBCOLOR(230, 232, 241);
    [self.view addSubview:firstLineView];
    
    UILabel *qiugouriqiLabel = [[UILabel alloc] initWithFrame:CGRectMake(10, firstLineView.bottom+3, kFiveLabelWidth, 20)];
    qiugouriqiLabel.font = Font(12);
    qiugouriqiLabel.textAlignment = NSTextAlignmentCenter;
    qiugouriqiLabel.text = @"求购日期";
    [self.view addSubview:qiugouriqiLabel];
    
    UILabel *fabudanshuLabel = [[UILabel alloc] initWithFrame:CGRectMake(qiugouriqiLabel.right+kMarginLeft, firstLineView.bottom+3, kFiveLabelWidth, 20)];
    fabudanshuLabel.font = Font(12);
    fabudanshuLabel.textAlignment = NSTextAlignmentCenter;
    fabudanshuLabel.text = @"发布单数";
    [self.view addSubview:fabudanshuLabel];
    
    UILabel *suohuodanshuLabel = [[UILabel alloc] initWithFrame:CGRectMake(fabudanshuLabel.right+kMarginLeft, firstLineView.bottom+3, kFiveLabelWidth, 20)];
    suohuodanshuLabel.font = Font(12);
    suohuodanshuLabel.textAlignment = NSTextAlignmentCenter;
    suohuodanshuLabel.text = @"锁货单数";
    [self.view addSubview:suohuodanshuLabel];
    
    UILabel *chengjiaodanshuLabel = [[UILabel alloc] initWithFrame:CGRectMake(suohuodanshuLabel.right+kMarginLeft, firstLineView.bottom+3, kFiveLabelWidth, 20)];
    chengjiaodanshuLabel.font = Font(12);
    chengjiaodanshuLabel.textAlignment = NSTextAlignmentCenter;
    chengjiaodanshuLabel.text = @"成交单数";
    [self.view addSubview:chengjiaodanshuLabel];
    
    UILabel *chengjiaolvLabel = [[UILabel alloc] initWithFrame:CGRectMake(chengjiaodanshuLabel.right+kMarginLeft, firstLineView.bottom+3, kFiveLabelWidth, 20)];
    chengjiaolvLabel.font = Font(12);
    chengjiaolvLabel.textAlignment = NSTextAlignmentCenter;
    chengjiaolvLabel.text = @"成交率";
    [self.view addSubview:chengjiaolvLabel];
    
    UIView *secondLineView = [[UIView alloc] initWithFrame:CGRectMake(0, chengjiaolvLabel.bottom+3, self.view.width, 0.5)];
    secondLineView.backgroundColor = RGBCOLOR(230, 232, 241);
    [self.view addSubview:secondLineView];
    
    UITableView *baobiaoTableView = [[UITableView alloc] initWithFrame:CGRectMake(0, secondLineView.bottom, self.view.width, self.view.height-secondLineView.bottom) style:UITableViewStylePlain];
    baobiaoTableView.delegate = self;
    baobiaoTableView.dataSource = self;
    baobiaoTableView.separatorStyle = NO;
    [self.view addSubview:baobiaoTableView];
    self.baobiaoTableView = baobiaoTableView;
    
    // 初始化参数
    _keyType = day;
    _keyDate = nil;
    _tongJiResultModel = [[TongJiResultModel alloc] init];
    _dataSourceArray = [NSMutableArray array];
    
    //放置下拉上拉刷新控件
    __weak TongJiBaoBiaoViewController *weakSelf = self;
    [self.baobiaoTableView addPullToRefreshWithActionHandler:^{
        [weakSelf insertRowAtTop];
    }];

    //请求数据
    [self insertRowAtTop];
}

- (void)insertRowAtTop {
    __weak TongJiBaoBiaoViewController *weakSelf = self;
    [weakSelf.baobiaoTableView beginUpdates];
    
    NSMutableDictionary *tempDictionary = [[NSMutableDictionary alloc] init];
    NSNumber *dateType = [NSNumber numberWithInteger:_keyType];
    [tempDictionary setValue:dateType forKey:@"key_type"];//1:按日汇总,7:按周汇总,30:按月汇总
    [tempDictionary setValue:_nowDateString forKey:@"key_date"];
    if (_keyDate) {
        [tempDictionary setValue:_keyDate forKey:@"key_date"];
    }
  
    [Controller requestWithURL:PostQueryUserSurroundSuccessMall jsondic:tempDictionary finishBlock:^(ClassData* data) {
        if (data.number.intValue == 0) {
            _tongJiResultModel = [TongJiResultModel mj_objectWithKeyValues:data.data];
            [self setUIData:_tongJiResultModel.STATISTICS_COUNT];
            _dataSourceArray = _tongJiResultModel.STATISTICS_LIST;
            if (_dataSourceArray.count > 1) {
                switch (_paiXuMethod) {
                    case timeTop2Bottom:
                        weakSelf.dataSourceArray = [weakSelf sortDataByTimeTop2Bottom:weakSelf.dataSourceArray];
                        break;
                    case timeBottom2Top:
                        weakSelf.dataSourceArray = [weakSelf sortDataByTimeBottom2Top:weakSelf.dataSourceArray];
                        break;
                    case orderNumberBottom2Top:
                        weakSelf.dataSourceArray = [weakSelf sortDataByOrderNumberBottom2Top:weakSelf.dataSourceArray];
                        break;
                    case orderNumberTop2Bottom:
                        weakSelf.dataSourceArray = [weakSelf sortDataByOrderNumberTop2Bottom:weakSelf.dataSourceArray];
                        break;
                        
                    default:
                        break;
                }
            }
            dispatch_async(dispatch_get_main_queue(), ^{
                [weakSelf.baobiaoTableView reloadData];
            });

            //判断 是否  有 无数据
            if (_dataSourceArray.count==0) {
                if (la) {
                    [la removeFromSuperview];
                }
                
                la=[[labelview alloc]init];
                [la setimage:nil tit:@"暂无数据" buttontit:nil frem:CGRectMake(0, 0, self.view.frame.size.width, self.view.frame.size.height)];
                la.backgroundColor= [UIColor colorWithRed:230/255.0 green:232/255.0 blue:241/255.0  alpha:1];
                la.label.frame=CGRectMake(50, 100, self.view.frame.size.width-100, 40);
                [weakSelf.baobiaoTableView addSubview:la];
                
            }else{
                if (la) {
                    [la removeFromSuperview];
                }
            }
            
        } else {
            ALERTSHOW(data.message);
        }
    }];
    
//     3. 结束刷新(相当于动画)
    [weakSelf.baobiaoTableView endUpdates];
    [weakSelf.baobiaoTableView.pullToRefreshView stopAnimating];
}

#pragma mark 私有方法 设置UI的数据显示
- (void)setUIData:(StatisticsCountModel *)statisticsCountModel {
    self.numberOfOrderLabel.text = [NSString stringWithFormat:@"%@单", statisticsCountModel.SCCUESS_NUM];
    float increaseRate = statisticsCountModel.INCREASING_NUM.floatValue;
    //判断成交率箭头
    if (increaseRate < 0) {
        _jiantouImage.hidden = NO;
        _jiantouImage.image = [UIImage imageNamed:@"bottomimage"];
    } else if (increaseRate == 0) {
        _jiantouImage.hidden = YES;
    } else {
        _jiantouImage.hidden = NO;
        _jiantouImage.image = [UIImage imageNamed:@"topimage"];
    }
 
    //过滤"-"号
    if([statisticsCountModel.INCREASING_NUM rangeOfString:@"-"].location !=NSNotFound) {
       statisticsCountModel.INCREASING_NUM = [statisticsCountModel.INCREASING_NUM stringByReplacingOccurrencesOfString:@"-" withString:@""];
    }
    self.compareOrderLabel.text = [NSString stringWithFormat:@"%@单", statisticsCountModel.INCREASING_NUM];
    CGSize tempSize = [self.compareOrderLabel boundingRectWithSize:CGSizeMake(CGFLOAT_MAX, 15)];
    self.compareOrderLabel.frame = CGRectMake(kOneThirdWidth*2+42, self.numberOfOrderLabel.top, tempSize.width, 15);
    self.jiantouImage.frame = CGRectMake(self.compareOrderLabel.right+2, self.numberOfOrderLabel.top-2, 10, 20);
    
    [_pcCircle removeFromSuperview];
    _pcCircle = [[PCCircle alloc] initWithFrame:CGRectMake(self.view.width/2-100, _numberOfOrderLabel.bottom+15, 200, 200)];
    
    NSDecimalNumber *everyON = [[NSDecimalNumber alloc]initWithString:[NSString stringWithFormat:@"%f",statisticsCountModel.SCCUESS_RATE]];
    NSDecimalNumber *yibai = [[NSDecimalNumber alloc] initWithString:@"100"];
    
    NSDecimalNumber *jieguo = [everyON decimalNumberByDividingBy:yibai];
    
    _pcCircle.percentage = jieguo.floatValue;                               //百分比数值
    //    _pcCircle.percentage =1;
    _pcCircle.lineWith = 10;                                     //线宽
    _pcCircle.fillColor = RGBCOLOR(255, 255, 255);               //填充颜色
    _pcCircle.unfillColor = RGBACOLOR(173, 219, 238, 0.5);       //未填充颜色
    _pcCircle.startAngle = 170;                                  //百分百的圆环起点
    _pcCircle.endInnerAngle = 370;                               //百分百的圆环终点
    [self.navcBar addSubview:_pcCircle];
}

#pragma mark - viewDidLoad methods
#pragma mark pop返回
- (void)backLogin {
    [self.navigationController popViewControllerAnimated:YES];
}

#pragma mark 具体委托方法
- (void)segmentAction:(UISegmentedControl *)segmentedControl {
    NSInteger index = segmentedControl.selectedSegmentIndex;
    switch (index) {
        case 0:
            _keyType = day;
            _paimingLabel.text = @"日成单排名";
            self.monthLabel.hidden = NO;
            break;
        case 1:
            _keyType = weak;
            _paimingLabel.text = @"周成单排名";
            self.monthLabel.hidden = NO;
            break;
        case 2:
            _keyType = month;
            _paimingLabel.text = @"月成单排名";
            self.monthLabel.hidden = YES;
            break;
        default:
            break;
    }
//    _keyDate = nil;
    _customDatePickerView = nil;
    [self insertRowAtTop];
}

#pragma mark 选择排序方法
- (void)selectPaiXuMethod {
    self.window = [UIApplication sharedApplication].keyWindow;
    [self.window addSubview:self.mengbanView];
    [self.mengbanView addSubview:self.customPaiXuPickerView];
}

#pragma mark 
- (void)selectTime {
    self.window = [UIApplication sharedApplication].keyWindow;
    [self.window addSubview:self.mengbanView];
    [self.mengbanView addSubview:self.customDatePickerView];
}

#pragma mark - TableView DataSource
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return _dataSourceArray.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    TongJiBaoBiaoItemTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:kTongJiBaoBiaoItemTableViewCell];
    if (!cell) {
        cell = [[TongJiBaoBiaoItemTableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:kTongJiBaoBiaoItemTableViewCell];
    }
    StatisticsModel *statisticsModel = self.dataSourceArray[indexPath.row];
    cell.statisticsModel = statisticsModel;
    return cell;
}

#pragma mark - UITableViewDelegate
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    return 30;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    TongJiBaoBiaoListViewController *tongJiBaoBiaoListViewController = [[TongJiBaoBiaoListViewController alloc] init];
    tongJiBaoBiaoListViewController.statisticsModel = self.dataSourceArray[indexPath.row];
    tongJiBaoBiaoListViewController.date_type = _keyType;
    [self.navigationController pushViewController:tongJiBaoBiaoListViewController animated:YES];
}

#pragma mark - lazy load
- (UIView *)mengbanView {
    if (!_mengbanView) {
        _mengbanView = [[UIView alloc] initWithFrame:[UIScreen mainScreen].bounds];
        _mengbanView.backgroundColor = [UIColor colorWithWhite:0.05f alpha:0.3f];// 此行代码牛逼,解决了下面View透明,上面View不透明的问题
        _mengbanView.userInteractionEnabled = YES;
        UITapGestureRecognizer *gesture = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(closeIt)];
        gesture.delegate = self;
        [_mengbanView addGestureRecognizer:gesture];
        self.tapGestureRecognizer = gesture;
    }
    return _mengbanView;
}

- (CustomDatePickerView *)customDatePickerView {
    if (!_customDatePickerView) {
        _customDatePickerView = [[CustomDatePickerView alloc] initWithFrame:CGRectMake(0, 0, self.view.width-40, 276)];
        _customDatePickerView.center = self.view.center;
        _customDatePickerView.backgroundColor = [UIColor whiteColor];
        
        __block TongJiBaoBiaoViewController *weakSelf = self;
        _customDatePickerView.cancelActionBlock = ^() {
            [weakSelf closeIt];
        };
        _customDatePickerView.conformActionBlock = ^(NSString *dateTimeString) {
            [weakSelf closeIt];
            NSDate *paramDate = [NSDate parseDate:dateTimeString];
            if (paramDate) {
                NSCalendar *calendar = [NSCalendar currentCalendar];
                NSUInteger unitFlags = NSCalendarUnitYear | NSCalendarUnitMonth | NSCalendarUnitDay | NSCalendarUnitHour | NSCalendarUnitMinute | NSCalendarUnitSecond;
                NSDateComponents *dateComponent = [calendar components:unitFlags fromDate:paramDate];
                int year = (int)[dateComponent year];
                int month = (int)[dateComponent month];
                weakSelf.yearLabel.text = [NSString stringWithFormat:@"%d年", year];
                weakSelf.monthLabel.text = [NSString stringWithFormat:@"%d月", month];
                _keyDate = dateTimeString;
                [weakSelf insertRowAtTop];
            }
        };
        if (_keyType != month) {
            _customDatePickerView.dataSourceIsDictionaryOrArray = kDictionary;
            _customDatePickerView.dataSourceDictionary = self.customDatePickerViewDataSourceDictionary;
        } else {
            _customDatePickerView.dataSourceIsDictionaryOrArray = kArray;
            _customDatePickerView.dataSourceArray = self.customDatePickerViewDataSourceArray;
        }
    }
    return _customDatePickerView;
}

- (CustomPaiXuPickerView *)customPaiXuPickerView{
    if (!_customPaiXuPickerView) {
        _customPaiXuPickerView = [[CustomPaiXuPickerView alloc] initWithFrame:CGRectMake(0,0, self.view.width-40, 276)];
        _customPaiXuPickerView.center = self.view.center;
        _customPaiXuPickerView.backgroundColor = [UIColor whiteColor];
        __block TongJiBaoBiaoViewController *weakSelf = self;
        _customPaiXuPickerView.cancelActionBlock = ^() {
            [weakSelf closeIt];
        };
        _customPaiXuPickerView.conformActionBlock = ^(int row) {
            [weakSelf closeIt];
            if (self.dataSourceArray.count > 1) {
                switch (row) {
                    case 0:
                        _paiXuMethod = timeTop2Bottom;
                        weakSelf.dataSourceArray = [weakSelf sortDataByTimeTop2Bottom:weakSelf.dataSourceArray];
                        break;
                    case 1:
                        _paiXuMethod = timeBottom2Top;
                        weakSelf.dataSourceArray = [weakSelf sortDataByTimeBottom2Top:weakSelf.dataSourceArray];
                        break;
                    case 2:
                        _paiXuMethod = orderNumberBottom2Top;
                        weakSelf.dataSourceArray = [weakSelf sortDataByOrderNumberBottom2Top:weakSelf.dataSourceArray];
                        break;
                    case 3:
                        _paiXuMethod = orderNumberTop2Bottom;
                        weakSelf.dataSourceArray = [weakSelf sortDataByOrderNumberTop2Bottom:weakSelf.dataSourceArray];
                        break;
                        
                    default:
                        break;
                }
                dispatch_async(dispatch_get_main_queue(), ^{
                    [weakSelf.baobiaoTableView reloadData];
                });
            }
            
            NSArray *pickerArray = [NSArray arrayWithObjects:@"按时间从高到低",@"按时间从低到高",@"按成单数从低到高",@"按成单数从高到低", nil];
            [weakSelf.paixuButton setTitle:pickerArray[row] forState:UIControlStateNormal];
            if (row == 0 || row == 3) {
                [weakSelf.paixuButton setImage:[UIImage imageNamed:@"fromtobottomtotop"] forState:UIControlStateNormal];
            } else {
                [weakSelf.paixuButton setImage:[UIImage imageNamed:@"fromtoptobottom"] forState:UIControlStateNormal];
            }
        };
    }
    return _customPaiXuPickerView;
}

- (void)closeIt {
    [_customDatePickerView removeFromSuperview];
    [_customPaiXuPickerView removeFromSuperview];
    [_mengbanView removeFromSuperview];
}

#pragma mark - 排序算法
#pragma mark 按时间从高到低
- (NSMutableArray *)sortDataByTimeTop2Bottom:(NSMutableArray *)dataArray {
    NSArray *sortedArray = [dataArray sortedArrayUsingComparator: ^NSComparisonResult(StatisticsModel *staModel1, StatisticsModel *staModel2) {
        return [[NSDate parseDate:staModel2.START_TIME] compare: [NSDate parseDate:staModel1.START_TIME]];
    }];
    
    return [sortedArray mutableCopy];
}

#pragma mark 按时间从低到高
- (NSMutableArray *)sortDataByTimeBottom2Top:(NSMutableArray *)dataArray {
    NSArray *sortedArray = [dataArray sortedArrayUsingComparator: ^NSComparisonResult(StatisticsModel *staModel1, StatisticsModel *staModel2) {
        return [[NSDate parseDate:staModel1.START_TIME] compare: [NSDate parseDate:staModel2.START_TIME]];
    }];
    
    return [sortedArray mutableCopy];
}

#pragma mark 按成单数从低到高
- (NSMutableArray *)sortDataByOrderNumberBottom2Top:(NSMutableArray *)dataArray {
    NSArray *sortedArray = [dataArray sortedArrayUsingComparator: ^NSComparisonResult(StatisticsModel *staModel1, StatisticsModel *staModel2) {
        return [[NSNumber numberWithInt:staModel1.SUCCESS_NUM] compare: [NSNumber numberWithInt:staModel2.SUCCESS_NUM]];
    }];
    
    return [sortedArray mutableCopy];
}

#pragma mark 按成单数从高到低
- (NSMutableArray *)sortDataByOrderNumberTop2Bottom:(NSMutableArray *)dataArray {
    NSArray *sortedArray = [dataArray sortedArrayUsingComparator: ^NSComparisonResult(StatisticsModel *staModel1, StatisticsModel *staModel2) {
        return [[NSNumber numberWithInt:staModel2.SUCCESS_NUM] compare: [NSNumber numberWithInt:staModel1.SUCCESS_NUM]];
    }];
    
    return [sortedArray mutableCopy];
}

#pragma mark 返回自定义时间选择器的数据源数组
- (NSMutableArray *)customDatePickerViewDataSourceArray {
    if (!_customDatePickerViewDataSourceArray) {
        _customDatePickerViewDataSourceArray = [NSMutableArray array];
        NSDate *date = [NSDate date];
        NSString *dateTimeString = [NSDate formatDate:date];
        if (dateTimeString) {
            NSArray *tempArray = [dateTimeString componentsSeparatedByString:@"-"];
            int year = [tempArray[0] intValue];
            for (int i = kBeginYear; i <= year; i++) {
                [_customDatePickerViewDataSourceArray addObject:[NSString stringWithFormat:@"%d", i]];
            }
        } else {
            return nil;
        }
    }
    return [_customDatePickerViewDataSourceArray mutableCopy];
}

#pragma mark 返回自定义时间选择器的数据源字典
- (NSMutableDictionary *)customDatePickerViewDataSourceDictionary {
    if (!_customDatePickerViewDataSourceDictionary) {
        _customDatePickerViewDataSourceDictionary = [NSMutableDictionary dictionary];
        NSDate *now = [NSDate date];
        NSCalendar *calendar = [NSCalendar currentCalendar];
        NSUInteger unitFlags = NSCalendarUnitYear | NSCalendarUnitMonth | NSCalendarUnitDay | NSCalendarUnitHour | NSCalendarUnitMinute | NSCalendarUnitSecond;
        NSDateComponents *dateComponent = [calendar components:unitFlags fromDate:now];
        int year = (int)[dateComponent year];
        int month = (int)[dateComponent month];
        for (int i = kBeginYear; i <= year; i++) {
            if (i == year) {
                NSMutableArray *mua = [NSMutableArray array];
                for (int j = 1; j <= month; j++) {
                    [mua addObject:[NSString stringWithFormat:@"%d", j]];
                }
                
                [_customDatePickerViewDataSourceDictionary setObject:mua forKey:[NSString    stringWithFormat:@"%d",i]];
            } else {
                NSMutableArray *mua = [NSMutableArray array];
                for(int j = 1; j <= 12; j++) {
                    [mua addObject:[NSString stringWithFormat:@"%d",j]];
                }
                [_customDatePickerViewDataSourceDictionary setObject:mua forKey:[NSString    stringWithFormat:@"%d",i]];
            }
        }
    }
    return [_customDatePickerViewDataSourceDictionary mutableCopy];
}

@end
